package com.qing.controller;

import com.qing.domain.User;
import com.qing.domain.UserLoginLog;
import com.qing.service.LoginLogService;
import com.qing.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;

@Controller
@RequestMapping("/user")
public class UserController {
    private final UserService userService;
    private final LoginLogService loginLogService;
    @Autowired
    public UserController(UserService userService,LoginLogService loginLogService){
        this.userService=userService;
        this.loginLogService=loginLogService;
    }

    @RequestMapping(value = "/userLogin",method = RequestMethod.POST)
    public String userLogin(User loginUser, HttpServletRequest request){
        User user=userService.getUserByUserName(loginUser.getUserName());
        String password="";//先取得数据库正确密码

        System.out.println(loginUser);      System.out.println(user);
        if(user!=null){ password=userService.getPassword(user.getUserName());}
        if(user!=null&&loginUser.getPassword().equals(password)){
            String userName=user.getUserName();//如果密码正确，获得基本信息
            String lastIp=request.getRemoteAddr();
            Timestamp lastLoginTime=new Timestamp(System.currentTimeMillis());
            //更新用户基本信息
            user.setLastIp(lastIp);
            user.setLastLoginTime(lastLoginTime);
            user.setCredit(5 + user.getCredit());
            userService.updateUserByUser(user);
            // 更新用户登录日志
            UserLoginLog userLoginLog = new UserLoginLog();
            userLoginLog.setUserName(userName);
            userLoginLog.setLoginIp(lastIp);
            userLoginLog.setLoginDateTime(lastLoginTime);
            loginLogService.addUserLoginLog(userLoginLog);
            // 登陆成功，跳转到主页
            request.getSession().setAttribute("userName",user.getUserName());
            request.getSession().setAttribute("user",user);//这样不安全是吧？？？
            System.out.println(user);
            System.out.println(request.getSession().getAttribute("user"));
            if(user.getUserType()==0){
                return "user/adminpage";//管理员页面
            }
            return "user/userpage";//return "redirect:/";（两个controller之间重定向）
        }
        // 登录失败，跳转页面
        request.setAttribute("Msg", "登录失败");
        return "error";
    }
}
